import asyncio
import json
from tornado import gen
from baseHandler import Application, PayHandler, init_logger, http_result

logger = init_logger("unionpayquick", "/data/log/query/query.log")


class QueryHandler(PayHandler):
    @gen.coroutine
    def post(self):
        exited = yield self.merchant_exit()
        if not exited:
            logger.info("商户不存在")
            return self.write(json.dumps({"message": "商户不存在", "ret": -1}))
        if not self.check_ip():
            return self.write(json.dumps({"message": "ip错误", "ret": -1}))
        if not self.check_sign():
            logger.info("签名验证失败")
            return self.write(json.dumps({"message": "签名验证失败", "ret": -1}))
        data = self.decrypt()
        if not data:
            return self.write({"message": "解密失败", "ret": -1})
        data = json.loads(data)
        ordernumber = data['ordernumber']
        logger.info("%s|查询|订单号%s", self.merchantid, ordernumber)
        input_json = {
            "OPERPASS": "f15dbcb3154d37e4a183a350e4e8a15dde16a175",
            "FUNCTYPE": "QUER",
            "DEPTID": "800001",
            "OPERID": "9527",
            "FUNCCODE": "100202",
            "REQINFO": {
                "MERCHANTORDERNO": ordernumber,
                "MERCHANTID": self.merchantid
            }
        }
        logger.info(input_json)
        core_response = yield from self.pay_core("PAY_UNIONPAY_ENTRUST_QUERY", input_json)
        logger.info(core_response)
        if core_response["RESPCODE"] != "10000000":
            return self.write({"ret": -1, "message": core_response["MESSAGE"]})

        channel = core_response.get("PAYCHANNEL", "")
        logger.info(channel)
        url = yield self.get_channel_redis(channel + '_Q')
        logger.info(url)
        if not url:
            return self.write({"ret": -1, "message": "未知错误"})

        response = yield http_result(url, core_response)

        if response.code == 200 and response.body.startswith(b'{'):
            channel_result = json.loads(response.body.decode("utf-8"))
            orderstate = channel_result["orderstate"]
            logger.info('%s|银联同名卡进出|订单%s|支付结果%s', self.merchantid, data['ordernumber'], orderstate)
        else:
            orderstate = "9"
            if response.code == 200:
                message = response.body.decode('utf-8')
            else:
                message = '500%s' % response.code
            channel_result = {"message": message}
            logger.info('%s|银联同名卡进出|订单%s|支付结果%s|%s', self.merchantid, data['ordernumber'], orderstate, message)

        input_json = {
            "DEPTID": "800001",
            "OPERID": "9527",
            "FUNCTYPE": "RESP",
            "FUNCCODE": "300101",
            "OPERPASS": "f15dbcb3154d37e4a183a350e4e8a15dde16a175",
            "REQINFO": {
                "OUTERORDERNO": core_response["OUTERORDERNO"],
                # "OPMONEY": str(core_response["OPMONEY"]),
                "PAYORDERNO": core_response["OUTERORDERNO"],
                "ORDERSTATE": orderstate,
                "PAYINFO": channel_result.get('message', ""),
            }
        }
        logger.info(input_json)
        result = yield from self.pay_core("PAY_UNIONPAY_ENTRUST_RES", input_json)
        logger.info(result)

        result.update({"MERCHANTID": self.merchantid})
        # if result["RETREDIRECT"] == "PAY.CORE.EBS" and result["MESSAGE"] == "SUCCESS":
        rsp_obj = {
            'ordernumber': core_response['MERCHANTORDERNO'],
            "payorderno": core_response["OUTERORDERNO"],
            # "amount": result['OPMONEY'],
            "orderstate": orderstate,
            "resptime": core_response.get("RESPTIME", "")
        }
        return_obj = self.niti_data(rsp_obj, result)
        return_obj.update({"ret": 0, "message": "success"})

        return self.write(return_obj)
        # else:
        #     return self.write({"ret": -1, "message": result["MESSAGE"]})


class QuickQueryHandler(PayHandler):
    @gen.coroutine
    def post(self):
        exited = yield self.merchant_exit()
        if not exited:
            logger.info("商户不存在")
            return self.write(json.dumps({"message": "商户不存在", "ret": -1}))
        if not self.check_ip():
            return self.write(json.dumps({"message": "ip错误", "ret": -1}))
        if not self.check_sign():
            logger.info("签名验证失败")
            return self.write(json.dumps({"message": "签名验证失败", "ret": -1}))
        data = self.decrypt()
        if not data:
            return self.write({"message": "解密失败", "ret": -1})
        data = json.loads(data)
        ordernumber = data['ordernumber']
        logger.info("%s|查询|订单号%s", self.merchantid, ordernumber)
        input_json = {
            "OPERPASS": "f15dbcb3154d37e4a183a350e4e8a15dde16a175",
            "FUNCTYPE": "QUER",
            "DEPTID": "800001",
            "OPERID": "9527",
            "FUNCCODE": "100202",
            "REQINFO": {
                "MERCHANTORDERNO": ordernumber,
                "MERCHANTID": self.merchantid
            }
        }
        logger.info(input_json)
        core_response = yield from self.pay_core("PAY_UNIONPAY_QUICK_QUERY", input_json)
        logger.info(core_response)

        if core_response["RESPCODE"] != "10000000":
            return self.write({"ret": -1, "message": core_response["MESSAGE"]})

        if core_response.get("PAYSTATE") not in ('9', '8'):
            orderstate = core_response.get("PAYSTATE", "9")
        else:

            if core_response.get("PAYCHANNEL") in ("JN.PAY.UNIONPAY.DEBIT", "JN.PAY.UNIONPAY.CREDIT"):
                url = 'http://127.0.0.1:10020/jieniu/query'
            else:
                url = yield self.get_channel_redis(core_response.get("PAYCHANNEL", "") + '_Q')

            response = yield http_result(url, core_response)

            logger.info(response.body)
            if response.code == 200 and response.body.startswith(b'{'):
                channel_result = json.loads(response.body.decode("utf-8"))
                orderstate = channel_result["orderstate"]
                message = "none"
                logger.info('%s|银联进出|订单%s|支付结果%s|%s', self.merchantid, data['ordernumber'], orderstate,
                            channel_result.get("message"))
            else:
                orderstate = "9"
                if response.code == 200:
                    message = response.body.decode('utf-8')
                else:
                    message = '500%s' % response.code
                channel_result = {"message": message}
                logger.info('%s|银联同名卡进出|订单%s|支付结果%s|%s', self.merchantid, data['ordernumber'], orderstate, message)

            input_json = {
                "DEPTID": "800001",
                "OPERID": "9527",
                "FUNCTYPE": "NOTI",
                "FUNCCODE": '200101',
                "OPERPASS": "f15dbcb3154d37e4a183a350e4e8a15dde16a175",
                "REQINFO": {
                    'OUTERORDERNO': core_response['OUTERORDERNO'],
                    'PAYORDERNO': core_response['OUTERORDERNO'],
                    "ORDERSTATE": orderstate,
                    "OPMONEY": "",
                    "PAYINFO": message,
                }
            }
            # 发送到核心程序
            logger.info(input_json)
            result = yield from self.pay_core('PAY_UNIONPAY_QUICK_NOTIFY', input_json)
            logger.info(result)

        core_response.update({"MERCHANTID": self.merchantid})
        rsp_obj = {
            'ordernumber': core_response['MERCHANTORDERNO'],
            "payorderno": core_response["OUTERORDERNO"],
            # "amount": result['OPMONEY'],
            "orderstate": orderstate,
            "resptime": core_response.get("FHISTIME", "")
        }
        return_obj = self.niti_data(rsp_obj, core_response)
        return_obj.update({"ret": 0, "message": "success"})

        return self.write(return_obj)


if __name__ == "__main__":
    handlers = [

        (r"/pay/unionpay/query/entrust", QueryHandler),
        (r"/pay/unionpay/query/quick", QuickQueryHandler),
    ]

    logger.info("Run unionpay server ... http://127.0.0.1:9990")
    application = Application(handlers)
    application.listen(9990, address="127.0.0.1")

    loop = asyncio.get_event_loop()
    application.init_with_loop(loop)
    loop.run_forever()
